package com.taobao.open.action;

import java.text.ParseException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import utils.Util;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.ItemUpdateDelistingRequest;
import com.taobao.api.request.ItemsListGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.request.PromotionLimitdiscountGetRequest;
import com.taobao.api.request.UmpActivityAddRequest;
import com.taobao.api.request.UmpRangeAddRequest;
import com.taobao.api.request.UmpToolAddRequest;
import com.taobao.api.request.UmpToolsGetRequest;
import com.taobao.api.request.UserSellerGetRequest;
import com.taobao.api.response.ItemUpdateDelistingResponse;
import com.taobao.api.response.ItemsListGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.api.response.PromotionLimitdiscountGetResponse;
import com.taobao.api.response.UmpActivityAddResponse;
import com.taobao.api.response.UmpRangeAddResponse;
import com.taobao.api.response.UmpToolAddResponse;
import com.taobao.api.response.UmpToolsGetResponse;
import com.taobao.api.response.UserSellerGetResponse;
import com.taobao.open.javabean.Trade;
import com.taobao.ump.marketing.MarketingBuilder;

public class ShowAction extends ActionSupport
{
	private static final long serialVersionUID = 2388081757724332026L;
	protected static String url = "http://gw.api.tbsandbox.com/router/rest";// 沙箱环境调用地址
	protected static String appkey = "1021221687";
	protected static String secret = "sandboxb03df5f8cd9dc92ef08bb8f25";
	protected static String key = "";

	String check;

	public String getCheck()
	{
		return check;
	}

	public void setCheck(String check)
	{
		this.check = check;
	}

	/**
	 * 用户访问 将其top_session保存到session中以备后面使用
	 * 
	 * @return
	 * @throws ParseException
	 */
	public String login() throws ParseException
	{
		HttpServletRequest req = ServletActionContext.getRequest();
		HttpServletResponse rsp = ServletActionContext.getResponse();
		key = req.getParameter("top_session").toString();
		req.setAttribute("key", req.getParameter("top_session").toString());
		getname(req, rsp, req.getParameter("top_session").toString());

		// getTools(req, rsp, req.getParameter("top_session").toString());
		// addTools(req, rsp, req.getParameter("top_session").toString());
		// selectDiscountActivity(req, rsp, req.getParameter("top_session")
		// .toString());
		// addDiscountActivity(req, rsp, req.getParameter("top_session")
		// .toString());
		// addRangeUmp(req, rsp, req.getParameter("top_session").toString());
		return SUCCESS;
	}

	/**
	 * 填写活动基本信息
	 * 
	 * @return
	 */
	public String StepOne()
	{
		HttpServletRequest req = ServletActionContext.getRequest();
		req.setAttribute("name", ActionContext.getContext().getSession().get(
				"name").toString());
		req.setAttribute("title", Util.getDate() + "促销");
		return SUCCESS;
	}

	/**
	 * 选择参与活动的商品
	 * 
	 * @return
	 */
	public String StepTwo()
	{
		HttpServletRequest req = ServletActionContext.getRequest();
		HttpServletResponse rsp = ServletActionContext.getResponse();
		getinfo(req, rsp, key);
		req.setAttribute("name", ActionContext.getContext().getSession().get(
				"name").toString());
		return SUCCESS;
	}

	/**
	 * 创建打折活动
	 * 
	 * @return
	 */
	public String StepThree()
	{
		HttpServletRequest req = ServletActionContext.getRequest();
		HttpServletResponse rsp = ServletActionContext.getResponse();
		System.out.println("check=" + check);
		req.setAttribute("name", ActionContext.getContext().getSession().get(
				"name").toString());
		getList(req, rsp, key);
		return SUCCESS;
	}

	/**************************************************************************
	 * 
	 * 下面是具体相关方法
	 * 
	 * /************************************************************************
	 * /** 获取当前用户在售的所有商品
	 * 
	 * @param request
	 * @param response
	 * @param sessionKey
	 */
	public void getinfo(HttpServletRequest request,
			HttpServletResponse response, String sessionKey)
	{
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
		req.setFields("num_iid,title,price,pic_url");

		try
		{
			ItemsOnsaleGetResponse rsp = client.execute(req, sessionKey);
			System.out.println(rsp.getBody());
			Trade[] trades = new Trade[Integer.parseInt(rsp.getTotalResults()
					.toString())];
			System.out.println(rsp.getTotalResults());
			for (int i = 0; i < rsp.getTotalResults(); i++)
			{
				System.out.println(i);
				String picurl = "";
				Trade trade = new Trade();
				String NumIid = rsp.getItems().get(i).getNumIid().toString();
				String Title = rsp.getItems().get(i).getTitle().toString();
				String Price = rsp.getItems().get(i).getPrice().toString();
				if (rsp.getItems().get(i).getPicUrl() == null)
				{
					System.out.println("该商品没有图片");
				} else
				{
					picurl = rsp.getItems().get(i).getPicUrl().toString();
				}
				trade.setNum_iid(NumIid);
				trade.setTitle(Title);
				trade.setPrice(Price);
				trade.setPic_url(picurl);
				trades[i] = trade;
			}
			ArrayList list = (ArrayList) rsp.getItems();
			request.setAttribute("trades", trades);
			request.setAttribute("TotalResults", rsp.getTotalResults()
					.toString());
			request.setAttribute("taobaoResponse", rsp.getItems().get(0)
					.getNumIid().toString());
		} catch (ApiException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 下架单一商品
	 * 
	 * @param request
	 * @param response
	 */
	public void delist(HttpServletRequest request,
			HttpServletResponse response, String sessionKey)
	{
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		ItemUpdateDelistingRequest req = new ItemUpdateDelistingRequest();
		req.setNumIid(1500023052843L);
		try
		{
			ItemUpdateDelistingResponse rsp = client.execute(req, sessionKey);
			System.out.println(rsp.getBody());
		} catch (ApiException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 获取卖家的昵称
	 * 
	 * @param request
	 * @param response
	 */
	public void getname(HttpServletRequest request,
			HttpServletResponse response, String sessionKey)
	{
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		UserSellerGetRequest req = new UserSellerGetRequest();
		req.setFields("nick,sex");
		try
		{
			UserSellerGetResponse rsp = client.execute(req, sessionKey);
			request.setAttribute("name", rsp.getUser().getNick());
			ActionContext.getContext().getSession().put("name",
					rsp.getUser().getNick());
		} catch (ApiException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 批量获取商品信息
	 * 
	 * @param request
	 * @param response
	 * @param sessionKey
	 */
	public void getList(HttpServletRequest request,
			HttpServletResponse response, String sessionKey)
	{
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		ItemsListGetRequest req = new ItemsListGetRequest();
		req.setFields("num_iid,title,price,pic_url");
		req.setNumIids(check);
		Trade[] trades = new Trade[check.split(",").length];
		try
		{
			ItemsListGetResponse rsp = client.execute(req, sessionKey);
			System.out.println(rsp.getBody());
			System.out.println(check.split(",").length);

			for (int i = 0; i < check.split(",").length; i++)
			{
				Trade trade = new Trade();
				String NumIid = rsp.getItems().get(i).getNumIid().toString();
				String Title = rsp.getItems().get(i).getTitle().toString();
				String Price = rsp.getItems().get(i).getPrice().toString();
				String picurl = rsp.getItems().get(i).getPicUrl().toString();
				trade.setNum_iid(NumIid);
				trade.setTitle(Title);
				trade.setPrice(Price);
				trade.setPic_url(picurl);
				trades[i] = trade;
			}
			ArrayList list = (ArrayList) rsp.getItems();
			request.setAttribute("trades", trades);
			request.setAttribute("TotalResults", String.valueOf(check
					.split(",").length));
			request.setAttribute("taobaoResponse", rsp.getItems().get(0)
					.getNumIid().toString());
		} catch (ApiException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 获取当前店铺有那些优惠活动
	 * 
	 * @param request
	 * @param response
	 * @param sessionKey
	 * @throws ParseException
	 */
	public void selectDiscountActivity(HttpServletRequest request,
			HttpServletResponse response, String sessionKey)
			throws ParseException
	{
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		PromotionLimitdiscountGetRequest req = new PromotionLimitdiscountGetRequest();
		// req.setLimitDiscountId(95276548L);
		// req.setStatus("DOING");
		// Date dateTime = SimpleDateFormat.getDateTimeInstance().parse(
		// "2000-01-01 00:00:00");
		// req.setStartTime(dateTime);
		// Date dateT = SimpleDateFormat.getDateTimeInstance().parse(
		// "2000-01-01 00:00:00");
		// req.setEndTime(dateT);
		// req.setPageNumber(1L);
		try
		{
			PromotionLimitdiscountGetResponse rsp = client.execute(req,
					sessionKey);
			System.out
					.println("==================selectDiscountActivity===================");
			System.out.println(rsp.getBody());
			System.out.println(rsp.getTotalCount());
			request.setAttribute("DiscountActivityTotalCount", rsp
					.getTotalCount().intValue());
		} catch (ApiException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 新增优惠活动
	 * 
	 * @param request
	 * @param response
	 * @param sessionKey
	 * @throws ParseException
	 */
	public void addDiscountActivity(HttpServletRequest request,
			HttpServletResponse response, String sessionKey)
			throws ParseException
	{
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		UmpActivityAddRequest req = new UmpActivityAddRequest();
		req.setToolId(12345L);
		req.setContent("{'name':'test','desc':'test'}");
		try
		{
			UmpActivityAddResponse rsp = client.execute(req, sessionKey);
			System.out.println(rsp.getBody());
			System.out.println("ActId=" + rsp.getActId());
		} catch (ApiException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 添加活动范围
	 * 
	 * @param request
	 * @param response
	 * @param sessionKey
	 */
	public void addRangeUmp(HttpServletRequest request,
			HttpServletResponse response, String sessionKey)
	{
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		UmpRangeAddRequest req = new UmpRangeAddRequest();
		req.setActId(123456L);
		req.setType(1L);
		req.setIds("1500018172522,1500022596842");
		try
		{
			UmpRangeAddResponse rsp = client.execute(req, sessionKey);
			System.out.println(rsp.getBody());
			System.out.println(rsp.isSuccess());
		} catch (ApiException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 新增优惠工具
	 */
	public void addTools(HttpServletRequest request,
			HttpServletResponse response, String sessionKey)
	{
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		UmpToolAddRequest req = new UmpToolAddRequest();
		req.setContent("{'tool_name':'test','desc':'test_desc'}");
		MarketingBuilder builder = new MarketingBuilder();
		// String json = builder.build(marketingTool);
		// req.setContent(json);
		// UmpToolAddResponse responses = client.execute(req);

		// MetaData fullPromotion = ;
		// MarketingTool marketingTool = builder.createMarketingTool();
		// marketingTool.setOperationMeta(new MetaData<ActionDef>());

		new MarketingBuilder();
		try
		{
			UmpToolAddResponse rsp = client.execute(req);
			System.out.println(rsp.getBody());
			System.out.println("ToolId=" + rsp.getToolId());
		} catch (ApiException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 查询工具列表
	 * 
	 * @param request
	 * @param response
	 * @param sessionKey
	 */
	public void getTools(HttpServletRequest request,
			HttpServletResponse response, String sessionKey)
	{
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		UmpToolsGetRequest req = new UmpToolsGetRequest();
		try
		{
			UmpToolsGetResponse rsp = client.execute(req);
			System.out.println(rsp.getBody());
			System.out.println(rsp.getTools().get(0));
		} catch (ApiException e)
		{
			e.printStackTrace();
		}
	}

}
